package com.my.screenadapter.mywebview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.my.screenadapter.mscreen.MyScreen;
import com.my.screenadapter.R;
import com.my.screenadapter.View.ProgressWebView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @function 加载URL 测试H5 和其他URL
 * @created time ???
 * edit 2018-4-18 16:01:08
 * <p>
 * 1 //打开本包内asset目次下的test.html文件
 * wView.loadUrl（" file:///android_asset/test.html "）;
 * <p>
 * 2 //打开本地sd卡内的kris.html文件
 * wView.loadUrl（"content://com.android.htmlfileprovider/sdcard/kris.html"）;
 * <p>
 * 3//打开指定URL的html文件
 * wView.loadUrl（http://www.krislq.com/）;
 */
public class WebViewActivity extends Activity {

    public static final String bundle_Url_Type = "url_type";
    public static final String bundle_Url_Data = "url_data";
    public static final int bundle_Url_Type_Url = 0;
    public static final int bundle_Url_Type_Text = 1;
    private static final String TAG = "WebViewActivity";
    private static final int FILECHOOSER_RESULTCODE = 22;
    private static final int REQUEST_CODE_IMAGE_CAPTURE = 1;
    @BindView(R.id.et_url)
    EditText etUrl;
    @BindView(R.id.btn_loadUrl)
    Button btnLoadUrl;
    @BindView(R.id.btn_load_localurl)
    Button btnLoadLocalurl;
    @BindView(R.id.btn_refresh)
    Button btnRefresh;
    @BindView(R.id.tv_webinfo)
    TextView tvWebinfo;
    @BindView(R.id.my_web)
    WebView myWeb;
    @BindView(R.id.my_progressweb)
    ProgressWebView myProgressweb;
    //    private ProgressWebView webView;
    private WebView webView;
    private int myUrlType;
    private String myUrl;
    private ValueCallback<Uri[]> mUploadFileAnd5;
    private ValueCallback<Uri> mUploadMessage4;

    public static void getCookie(String url) {
        if (!TextUtils.isEmpty(url)) {
            CookieManager instance = CookieManager.getInstance();
            String cookie = instance.getCookie(url);
            Log.i(TAG, "url==  " + url + "  Cookie:===  " + cookie);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        if (intent != null) {
            Bundle extras = intent.getExtras();
            if (extras != null) {
                myUrlType = extras.getInt(bundle_Url_Type);
                myUrl = extras.getString(bundle_Url_Data);
            }
        }
        initView();
        mLoadUrl(myUrlType, myUrl);
    }

    public void setCacheDEFAULT(View v) {
        WebSettings settings = webView.getSettings();
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
    }

    public void setCacheCACHE_ELSE_NETWORK(View v) {
        WebSettings settings = webView.getSettings();
        settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    }

    public void setCacheCACHE_ONLY(View v) {
        WebSettings settings = webView.getSettings();
        settings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);
    }

    public void setCacheNO_CACHE(View v) {
        WebSettings settings = webView.getSettings();
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    }

    private void initView() {
        webView = (WebView) findViewById(R.id.my_web);
        WebSettings settings = webView.getSettings();
//        设置网页布局类型：
//        *  1、LayoutAlgorithm.NARROW_COLUMNS ： 适应内容大小
//        *  2、LayoutAlgorithm.SINGLE_COLUMN: 适应屏幕，内容将自动缩放  有些网页混乱！！！飞起
//        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setJavaScriptEnabled(true);
        settings.setAppCacheEnabled(false);//设置缓存
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);

        settings.setBlockNetworkImage(false);//


       /* 从Android5.0以后，当一个安全的站点（https）去加载一个非安全的站点（http）时，需要配置Webview加载内容的混合模式，一共有如下三种模式：
        MIXED_CONTENT_NEVER_ALLOW：Webview不允许一个安全的站点（https）去加载非安全的站点内容（http）,
            比如，https网页内容的图片是http链接。强烈建议App使用这种模式，因为这样更安全。
        MIXED_CONTENT_ALWAYS_ALLOW：在这种模式下，WebView是可以在一个安全的站点（Https）里加载非安全的站点内容（Http）,这是WebView最不安全的操作模式，尽可能地不要使用这种模式。
        MIXED_CONTENT_COMPATIBILITY_MODE：在这种模式下，当涉及到混合式内容时，WebView会尝试去兼容最新Web浏览器的风格。一些不安全的内容（Http）能被加载到一个安全的站点上（Https），而其他类型的内容将会被阻塞。这些内容的类型是被允许加载还是被阻塞可能会随着版本的不同而改变，并没有明确的定义。这种模式主要用于在App里面不能控制内容的渲染，但是又希望在一个安全的环境下运行。

        //在Android5.0以下，默认是采用的MIXED_CONTENT_ALWAYS_ALLOW模式，即总是允许WebView同时加载Https和Http；
        而从Android5.0开始，默认用MIXED_CONTENT_NEVER_ALLOW模式，即总是不允许WebView同时加载Https和Http。
     */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(
                    WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        if (MyScreen.getScreenWidthDp(this) >= 640) {
//            settings.setTextSize(WebSettings.TextSize.LARGER);//设置字体大小
            settings.setTextSize(WebSettings.TextSize.NORMAL);//设置字体大小
        } else {
            settings.setTextSize(WebSettings.TextSize.NORMAL);//设置字体大小
        }

//        settings.setGeolocationEnabled(true);//启用地理定位 The default is true.
//        settings.setAllowFileAccess(true);//允许访问文件数据 默认true
//        settings.setSaveFormData(true);// Sets whether the WebView should save form data. The default is true.
        //      自适应屏幕
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setJavaScriptEnabled(true);
//      设置可以支持缩放
//        settings.setSupportZoom(true);
//      设置出现缩放工具
//        settings.setBuiltInZoomControls(true);

        // TODO: 2018/4/4 WebViewClient
        // webView.loadUrl("http://202.127.42.178:4000/countryseed/SpeciesDemand/Default.aspx#");
        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                //注：在重写WebViewClient的onReceivedSslError方法时，
                // 注意一定要去除onReceivedSslError方法的super.onReceivedSslError(view, handler, error);，否则设置无效。
//                super.onReceivedSslError(view, handler, error);
                // handler.cancel();// Android默认的处理方式
                handler.proceed();// 接受所有网站的证书
                // handleMessage(Message msg);// 进行其他处理
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.e(TAG, "加载完成 onPageFinished: onPageFinished url===" + url);
                getCookie(url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Log.e(TAG, "开始加载 onPageStarted: url==" + url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                //                webView.loadUrl("error html"); 可以载入本地错误页，也可以自定义 view
                tvWebinfo.setText("加载失败：errorCode==" + errorCode + "\n" + "description==" + description);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);

            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                Log.e(TAG, "加载进度onProgressChanged: newProgress===" + newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                tvWebinfo.setText("网页的Title:" + title+"\n"+"Url== "+view.getUrl());
            }


            // For Android 5.0+
            @SuppressLint("NewApi")
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
//                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//                i.addCategory(Intent.CATEGORY_OPENABLE);
//                i.setType("*/*");
                if (mUploadFileAnd5 != null) {
                    mUploadFileAnd5.onReceiveValue(null);
                }
                mUploadFileAnd5 = filePathCallback;
                if ((fileChooserParams != null)
                        && (fileChooserParams.getAcceptTypes() != null)
                        && (fileChooserParams.getAcceptTypes().length > 0)) {
                    String fileType = fileChooserParams.getAcceptTypes()[0];
                    if (fileType.equals("image/*")) {
                        choicLocalImg(filePathCallback, fileChooserParams, WebViewActivity.this);
                    } else if (fileType.equals("audio/*")) {
                        choicLocalAudio(filePathCallback, fileChooserParams, WebViewActivity.this);
                    } else {
                        choicLocalFile(filePathCallback, fileChooserParams, WebViewActivity.this);
                    }

                }

                return true;

            }

            //For Android 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                Log.e(TAG, "4.1 openFileChoose(ValueCallback<Uri> uploadMsg, String acceptType, String capture)");
                if (mUploadMessage4 != null) {
                    mUploadMessage4.onReceiveValue(null);
                }
                mUploadMessage4 = uploadMsg;
                choicLocalFile(null, null, WebViewActivity.this);
            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                Log.e(TAG, "openFileChoose( ValueCallback uploadMsg, String acceptType )");
                if (mUploadMessage4 != null) {
                    mUploadMessage4.onReceiveValue(null);
                }
                mUploadMessage4 = uploadMsg;
                choicLocalFile(null, null, WebViewActivity.this);
            }

        });


        //回退键
        webView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {  //表示按返回键
                        webView.goBack();   //后退
                        return true;    //已处理
                    }
                }
                return false;
            }

        });

        //webview下载文件
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {

                Log.i(TAG, "需要下载的URL onDownloadStart:== " + url);
                // TODO: 2018/4/18 可以自己下载 自己需要处理notification
                //   也可以intent 浏览器下载
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage4 && null == mUploadFileAnd5) {
                return;
            }
            Uri uri = data == null || resultCode != RESULT_OK ? null : data
                    .getData();

            if (mUploadFileAnd5 != null) {

                mUploadFileAnd5.onReceiveValue(new Uri[]{uri});
            } else if (mUploadMessage4 != null) {
                if (uri == null) {
                    // mUploadMessage.onReceiveValue(imageUri);
                    mUploadMessage4.onReceiveValue(null);
                    mUploadMessage4 = null;
                } else {
                    mUploadMessage4.onReceiveValue(uri);
                    mUploadMessage4 = null;
                }

            }
        }
    }

    private void choicLocalFile(ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams, Activity activity) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        Intent chooser = Intent.createChooser(intent, null);
        startActivityForResult(chooser, FILECHOOSER_RESULTCODE);
    }

    private void choicLocalAudio(ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams, Activity activity) {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("audio/*");
        startActivityForResult(Intent.createChooser(i, "File Chooser"),
                FILECHOOSER_RESULTCODE);
    }

    private void choicLocalImg(ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams, Activity activity) {
//        if (Build.VERSION.SDK_INT >= 23) {
//            if (ContextCompat.checkSelfPermission(activity,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                    != PackageManager.PERMISSION_GRANTED) {
//
//                ActivityCompat.requestPermissions(activity,
//                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                        MY_PERMISSIONS_REQUEST_WRITE);
//            } else {
//                mSourceIntent = ImageUtil.choosePicture();
//                startActivityForResult(mSourceIntent, FILECHOOSER_RESULTCODE);
//            }
//        } else {
//            mSourceIntent = ImageUtil.choosePicture();
//            startActivityForResult(mSourceIntent, FILECHOOSER_RESULTCODE);
//        }


        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        Intent chooser = Intent.createChooser(intent, null);
        startActivityForResult(chooser, FILECHOOSER_RESULTCODE);
    }


    /**
     * 加载URL
     *
     * @param type
     * @param weburl
     */
    private void mLoadUrl(int type, String weburl) {

        if (!TextUtils.isEmpty(weburl)) {
            if (type == bundle_Url_Type_Url) {
                //WebView加载web资源
                webView.loadUrl(weburl);
            } else if (type == bundle_Url_Type_Text) {
                //加载html
//                webView.loadData(weburl,"text/html","utf-8");//在有些手机上会出现乱码，将方法变成
                webView.loadDataWithBaseURL(null, weburl, "text/html", "utf-8", null);//就可以解决这个问
            }
        }
    }

    @OnClick(R.id.btn_loadUrl)
    public void loadUrl(View v) {
        EditText viewById = (EditText) findViewById(R.id.et_url);
        String et_url = viewById.getText().toString().trim();
        if (TextUtils.isEmpty(et_url)) {
            Toast.makeText(this, "URL为空", Toast.LENGTH_SHORT).show();
            return;
        }
        webView.loadUrl(et_url);
    }

    @OnClick(R.id.btn_load_localurl)
    public void loadAssetHtml(View v) {
        webView.loadUrl("file:///android_asset/my.html");
    }

    @OnClick(R.id.btn_refresh)
    public void reLoad(View v) {
        String url = webView.getUrl() + "?&" + System.currentTimeMillis();
        Toast.makeText(this,"重新载入网址："+url,Toast.LENGTH_LONG).show();
        Log.i(TAG, "reLoad: Url=== "+url);
//        webView.reload();
        webView.loadUrl(url);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Log.i("info", "landscape"); // 横屏
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            Log.i("info", "portrait"); // 竖屏
//            mRelativeLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            Toast.makeText(WebViewActivity.this, "现在是竖屏", Toast.LENGTH_SHORT).show();
//            mRelativeLayout.setVisibility(View.VISIBLE);
        }
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//            mRelativeLayout.setVisibility(View.GONE);
            Toast.makeText(WebViewActivity.this, "现在是横屏", Toast.LENGTH_SHORT).show();
        }
    }

    public void saveCookie(String cookie) {
        String urlCookie = "UrlCookie";
        String mCookie = "mCookie";
        SharedPreferences sharedPreferences = getSharedPreferences(urlCookie, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString(mCookie, cookie);
        edit.commit();
    }

    public String getLocalSveCookie() {
        String urlCookie = "UrlCookie";
        String mCookie = "mCookie";
        SharedPreferences sharedPreferences = getSharedPreferences(urlCookie, Context.MODE_PRIVATE);
        return sharedPreferences.getString(mCookie, "");
    }


    /**
     * 在执行webview的loadurl之前，先执行
     * <p>
     * 有人说这个问题：
     * 设置cookie之后，是不能设置以下属性的，
     * 否则cookie是无效的(不只是这些属性，这里只是举例，最好的方式是在执行loadurl之前再设置cookie)
     * webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
     * webview.getSettings().setJavaScriptEnabled(true);
     * webview.getSettings().setDatabaseEnabled(true);
     * webview.getSettings().setDomStorageEnabled(true);
     * <p>
     * 这里提一下需要注意的几点问题：
     * 1.cookie同步的时候一定要loadurl()方法之前执行
     * 2.cookie同步好之后不能设置以上提到的属性，如果有需要一定要在同步之前设置
     * 3.
     * setCookie（）方法的cookie值读取到分号就结束了，不注意会导致部分cookie信息丢失
     * 4.setCookie（）方法，cookie的值如果是字符串的形式，不能直接截取拼接，那样会有问题（表面上看没问题），尤其是当cookie中包含多个信息时，一定要通过
     * StringBuilder的方式拼接
     * 5.cookie同步不能再onPageStarted()方法中执行，会有问题（之前偷懒统一在那里同步一次，结果被坑了）
     * <p>
     * ------更新--------
     * 在最近的项目中又发现一个新的问题，当后台有多台服务器的时候，cookie同步还是有问题的，
     * 尤其是当cookie信息不止一条的时候，按照上面的方法同步cookie发现cookie有丢失现象，
     * 经过反复折腾跟踪发现，有一个细节一定要重视，就是服务器返回的path和domain，
     * 这两个不容忽视，而安卓的webview在同步cookie的时候以分号结束为一个cookie，
     * 即使拼接cookie同步过去，没有path和domain服务器不认识，也是有问题的。
     * 多个cookie信息一定要分开对应自己的path和domain，每次setcookie（）都要拼接一条完整cookie信息，可以采用for循环的方式拼接多条cookie信息。
     *
     * @param url
     */
    public void syncCookie(String url) {
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();// 移除以前的session
        cookieManager.removeAllCookie();// 移除以前的cookie
        //创建一个拼接cookie的容器,为什么这么拼接，大家查阅一下http头Cookie的结构
        StringBuilder sbCookie = new StringBuilder();
        //具体格式可以查看 fiddler
//        sbCookie.append(_mApplication.getUserInfo().getSessionID());//拼接sessionId
//        sbCookie.append(String.format("userName=%s", "张三"));
        sbCookie.append(String.format("JSESSIONID=%s", "INPUT YOUR JSESSIONID STRING"));
        sbCookie.append(String.format(";domain=%s", "INPUT YOUR DOMAIN STRING"));
        sbCookie.append(String.format(";path=%s", "INPUT YOUR PATH STRING"));
        String cookieValue = sbCookie.toString();
        Log.i(TAG, "同步前的Cookie:== " + cookieManager.getCookie(url));
        Log.i(TAG, "拼接的cookie== " + cookieValue);
        cookieManager.setCookie(url, cookieValue);//为url设置cookie
        CookieSyncManager.getInstance().sync();//同步cookie
        String cookieAfter = cookieManager.getCookie(url);
        Log.i(TAG, "同步后的cookie:== " + cookieAfter);
    }

    @Override
    protected void onPause() {
//        webView.reload();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清除 显示
        if (webView != null) {
            webView.removeAllViews();
        }
        Window window = getWindow();
        if (window != null) {
            View decorView = window.getDecorView();
            if (decorView != null && decorView instanceof ViewGroup) {
                ((ViewGroup) decorView).removeAllViews();
            }
        }
    }
}
